<template>
  <el-form ref="form" label-width="120px" :rules="rules" :model="form">
    <el-form-item label="部门名称" prop="name">
      <el-input v-model="form.name" style="width:80%" placeholder="1-50个字符" />
    </el-form-item>

    <el-form-item label="部门编码" prop="code">
      <el-input v-model="form.code" style="width:80%" placeholder="1-50个字符" />
    </el-form-item>

    <el-form-item label="部门负责人" prop="manager">
      <el-select v-model="form.manager" style="width:80%" placeholder="请选择">
        <el-option v-for="item in list" :key="item.id" :value="item.username" :label="item.username" />
      </el-select>
    </el-form-item>

    <el-form-item label="部门介绍" prop="introduce">
      <el-input v-model="form.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" :rows="3" />
    </el-form-item>

    <el-form-item>
      <el-button type="info" @click="hCancel">取消</el-button>
      <el-button type="primary" @click="hSubmit">确定</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { getSimpleEmployee, addDepartment, getDepartmentById, updataDepartment } from '@/api/departments'

export default {
  props: {
    pid: {
      type: String,
      required: true
    },
    isEdit: {
      type: Boolean,
      required: true
    },
    originList: {
      type: Array,
      required: true
    }
  },
  data() {
    const validCode = (rule, value, callback) => {
      // console.log('12', value) // 要验证的值
      let codeList = this.originList.map(item => item.code)
      console.log(codeList) // 所有部门的编码

      // 如果是编辑 要排除当前正在编辑的部门编号
      if (this.isEdit) {
        // 过滤掉当前部门的编码 map得到部门编号列表
        codeList = this.originList.filter(item => item.id !== this.pid).map(item => item.code)
      }
      if (codeList.includes(value)) {
        callback(new Error(value + '已经存在'))
      } else {
        callback()
      }
    }

    const validName = (rule, value, callback) => {
      // value是要校验的名字
      // 添加时候：不能与现有的同级部门重名
      // 当前被点击的部门的id是this.pid
      // 找出子部门
      const nameList = this.originList.filter(item => item.pid !== this.pid).map(item => item.name)
      console.log(nameList)

      // this.pid是当前正在被编辑的部门编号
      if (this.isEdit) {
        // 如果是编辑 不能取的名字是同级名字和自己名字
        const item = this.originList.find(item => item.id === this.id).pid
        const pid = item.pid
        const nameList = this.originList.filter(item => item.pid === pid && item.id !== this.pid).map(item => item.name)
        console.log(nameList)
      }
      // 如果 value在nameList中存在  说明名字重复了
      if (nameList.includes(value)) {
        callback(new Error(value + '被占用'))
      } else {
        callback()
      }
    }
    return {
      rules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门名称要求1-50个字符', trigger: 'blur' },
          { validator: validName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门编码要求1-50个字符', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: 'change' }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: 'blur' },
          { min: 1, max: 300, message: '部门介绍要求1-300个字符', trigger: 'blur' }
        ]
      },
      form: {
        name: '', // 部门名称
        introduce: '', // 部门介绍
        manager: '', // 部门管理者
        code: '' // 部门编码
      },
      list: []
    }
  },
  created() {
    this.loadSimpleEmployee()
    // 如果是编辑 就发请求拿到部门数据
    if (this.isEdit) {
      this.loadDepartmentById()
    }
  },
  methods: {
    // 获取详情
    async loadDepartmentById() {
      const res = await getDepartmentById(this.pid)
      console.log('编辑', res)
      // 数据回填
      this.form = res.data
    },
    async loadSimpleEmployee() {
      const res = await getSimpleEmployee()
      this.list = res.data
    },
    async doAdd() {
      // 调用接口
      try {
        await addDepartment({ ...this.form, pid: this.pid })
        // 通知父组件操作成功
        this.$emit('success')
      } catch (err) {
        console.log(err)
      }
    },
    async doEdit() {
      try {
        await updataDepartment(this.form)
        this.$message({ type: 'success', message: '修改成功' })
        this.$emit('success')
      } catch (err) {
        console.log(err)
        this.$message({ type: 'error', message: err })
      }
    },
    hSubmit() {
      // 表单兜底校验
      this.$refs.form.validate(valid => {
        if (valid) {
          this.isEdit ? this.doEdit() : this.doAdd()
        }
      })
      if (this.isEdit) {
        this.doEdit()
      } else {
        this.doAdd()
      }
    },
    resetForm() {
      // 1.重置表单
      this.$refs.form.resetFields()
    },
    hCancel() {
      // 通知父组件关闭弹窗
      this.$emit('close')
    }
  }
}
</script>
